package server

import (
	"github.com/gin-gonic/gin"
	"time"
	"os/signal"
	"net/http"
	"os"
	"fmt"
	"context"
	"NicePay/utils"
)

func Serve() {
	srvConf := utils.GetConfig().Server

	gin.SetMode(srvConf.Mode)
	engine := gin.New()
	engine.Use(utils.Handler())
	engine.Use(gin.Recovery())
	regRoute(engine)

	srv := &http.Server{
		Addr:    fmt.Sprintf("%s:%d", srvConf.Address, srvConf.Port),
		Handler: engine,
	}

	if srvConf.NetTypes == "https" {
		go serveHTTPS(srv, srvConf.TlsCertFile, srvConf.TlsKeyFile)
	} else {
		go serveHTTP(srv)
	}
	utils.System("server running ...")

	// Wait for interrupt signal to gracefully shutdown the server
	quit := make(chan os.Signal)
	signal.Notify(quit, os.Interrupt)
	<-quit
	utils.System("Wait to shutdown server ...")

	ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
	defer cancel()
	srv.Shutdown(ctx)
	utils.System("Server existed")
}

func serveHTTP(srv *http.Server) {
	if err := srv.ListenAndServe(); err != nil {
		utils.Fatal(err)
	}
}

func serveHTTPS(srv *http.Server, certFile, keyFile string) {
	if err := srv.ListenAndServeTLS(certFile, keyFile); err != nil {
		utils.Fatal(err)
	}
}
